<template>
  <div :id="id" type="text/plain" class="my-ueditor"></div>
</template>

<script>
  import emitter from 'utils/emitter.js'
  const toolbars = {
    simple: [
      [
        'fullscreen', // 全屏
        'source', // html
        'undo', // 撤销
        'redo', // 重做
        'bold', // 加粗
        'italic', // 斜体
        'underline', // 下划线
        'forecolor', // 字体
        'insertorderedlist', // 有序列表
        'insertunorderedlist', // 无序列表
        'justifyleft', // 居左对齐
        'justifyright', // 居右对齐
        'justifycenter', // 居中对齐
        'justifyjustify', // 两端对齐
        'removeformat', // 清除格式
        'simpleupload', // 单图上传
        'insertimage' // 多图上传
      ]
    ]
  }
  window.CONST = {
    basePath: ''
  }
  
  export default {
    componentName: 'EEditor',
    mixins: [emitter],
    props: {
      value: {
        type: String
      },
      options: {
        type: Object,
        default () {
          return {}
        }
      },
      toolbars: {
        type: [String, Array],
        default: 'simple'
      },
      disabled: {
        type: Boolean,
        default: false
      },
      validateEvent: {
        type: Boolean,
        default: true
      },
      maxlength: {
        type: Number,
        default: 8000
      },
      headers: {
        type: Function
      },
      script: {
        type: Array,
        default () {
          return [
            '/static/ueditor/ueditor.config.js',
            '/static/ueditor/ueditor.all.min.js',
            '/static/ueditor/lang/zh-cn/zh-cn.js'
          ]
        }
      },
      getAction: {
        type: Function
      }
    },
    data () {
      return {
        id: this.unique()
      }
    },
    watch: {
      value (value) {
        if (this.$$ue && this.$$ue.getContent && value !== this.$$ue.getContent()) {
          this.$$ue.setContent(value)
        }
      },
      disabled (value) {
        if (value) {
          this.$$ue.setDisabled()
        } else {
          this.$$ue.setEnabled()
        }
      }
    },
    mounted () {
      this.loadScript(() => {
        this.initEditor()
      })
    },
    destroyed () {
      if (this.$$ue) {
        this.$$ue.destroy()
        this.$$ue = null
        window.onscroll = null
      }
    },
    methods: {
      initEditor () {
        let formatUrl = function (url) {
          let u = url.replace(/&&/g, '&')
          u = u.replace(/\?&/g, '?')
          u = u.replace(/&$/g, '')
          u = u.replace(/&#/g, '#')
          u = u.replace(/&+/g, '&')
          return u
        }
        let self = this
        window.UE.Editor.prototype.getActionUrl = this.getAction || function (action) {
          let headersStr = self.headers ? self.headers() : ''
          let actionName = this.getOpt(action) || action
          let imageUrl = this.getOpt('imageUrl')
          let serverUrl = this.getOpt('serverUrl')
          if (!serverUrl && imageUrl) {
            serverUrl = imageUrl.replace(/^(.*[\/]).+([\.].+)$/, '$1controller$2') //eslint-disable-line
          }
          if (serverUrl) {
            serverUrl = serverUrl + (serverUrl.indexOf('?') === -1 ? '?' : '&') + 'action=' + (actionName || '') + headersStr
            return formatUrl(serverUrl)
          } else {
            return ''
          }
        }
        this.$$UEReady = false
        let options = {
          /**
           * 使用传入的配置对象
           * maximumWords 涉及其他位置引用 暂时不整合进options
           * change by 何仕敬
           * 2017-12-5 version 2.3.0
           */
          ...this.options,
          maximumWords: this.maxlength
        }
        if (this.toolbars) {
          if (typeof this.toolbars === 'string') {
            options.toolbars = toolbars[this.toolbars]
          } else {
            options.toolbars = this.toolbars
          }
        }
        this.$$ue = window.UE.getEditor(this.id, options)
        this.$$ue.addListener('contentChange', this.handleChange)
        this.$$ue.addListener('afterEecCommand', this.handleChange)
        this.$$ue.addListener('ready', this.handleReady)
      },
      handleReady () {
        this.value && this.$$ue.setContent(this.value)
        this.$$UEReady = true
        if (this.disabled) {
          this.$$ue.setDisabled()
        }
      },
      handleChange (e) {
        if (this.$$UEReady) {
          let content = this.$$ue.getContent()
          let contentTxt = this.$$ue.getContentTxt()
          this.$emit('update:text', contentTxt)
          this.$emit('input', content).$emit('change', content)
          if (this.validateEvent) {
            this.dispatch('ElFormItem', 'el.form.change', [contentTxt])
            this.dispatch('ElFormItem', 'el.form.blur', [contentTxt])
          }
        }
      },
      loadScript (fn) {
        let self = this
        if (!window.UE) {
          if (this.$scriptIndex === undefined) {
            this.$scriptIndex = 0
          }
          let load = () => {
            let node = document.createElement('script')
            node.type = 'text/javascript'
            node.onload = () => {
              self.$scriptIndex++
              if (self.script[self.$scriptIndex]) {
                load()
              } else {
                fn && fn()
              }
            }
            node.src = this.script[this.$scriptIndex]
            document.querySelector('head').appendChild(node)
          }
          load()
        } else {
          fn && fn()
        }
      }
    }
  }
</script>
